import 'package:dio/dio.dart';

import 'cookie_intercetor.dart';
import 'http_method.dart';
import 'print_log_interceptor.dart';
import 'res_interceptor.dart';

class DioInstance {
  static DioInstance? _instance;

  DioInstance._();

  static DioInstance instance() {
    return _instance ??= DioInstance._();
  }

  final Dio _dio = Dio();
  final _defaultTime = const Duration(seconds: 30);

  initDio({
    required String baseUrl,
    String? method = HttpMethod.get,
    Duration? sendTimeout,
    Duration? connectTimeout,
    Duration? receiveTimeout,
    ResponseType? responseType = ResponseType.json,
    String? contentType,
  }) {
    _dio.options = BaseOptions(
      baseUrl: baseUrl,
      method: method,
      sendTimeout: sendTimeout ?? _defaultTime,
      connectTimeout: connectTimeout ?? _defaultTime,
      receiveTimeout: receiveTimeout ?? _defaultTime,
      responseType: responseType,
      contentType: contentType,
    );
    _dio.interceptors.add(PrintLogInterceptor());
    _dio.interceptors.add(CookieInterceptor());
    _dio.interceptors.add(ResponseInterceptor());
  }

  Future<Response> get({
    required String path,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.get(
      path,
      queryParameters: queryParameters,
      options: options,
      cancelToken: cancelToken,
    );
  }


  Future<Response> post({
    required String path,
    Map<String, dynamic>? queryParameters,
    Map<String, dynamic>? data,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    return await _dio.post(
      path,
      queryParameters: queryParameters,
      data: data,
      options: options ?? Options(method: HttpMethod.post),
      cancelToken: cancelToken,
    );
  }

  Future<Response> request({
    required String path,
    Map<String, dynamic>? queryParameters,
    Map<String, dynamic>? data,
    Options? options,
  }) async {
    return await _dio.request(
      path,
      queryParameters: queryParameters,
      data: data,
      options: options,
    );
  }
}
